package com.jdd.modules.mqtt.server.revice;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jdd.dao.entity.TDeviceCmdRequest;
import com.jdd.dao.entity.TDeviceCmdResponse;
import com.jdd.dao.service.TDeviceCmdRequestService;
import com.jdd.dao.service.TDeviceCmdResponseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: jdd-people-passage
 * @ClassName ReciveMqttQrResponseService
 * @description: 设备回复执行结果topic消息处理类
 * @author: zsj
 * @create: 2022-03-24 09:56
 * @Version 1.0
 **/
@Service("mqttFaceAckStrategy")
public class RuiKaReciveMqttFaceSnResponseServiceStrategy implements IReciveMqttBaseStrategy {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TDeviceCmdRequestService cmdRequestService;
    @Autowired
    private TDeviceCmdResponseService cmdResponseService;

    /**
     * 处理从mqtt接收到的设备执行命令结果回复消息接口
     *
     * @param message 消息
     * @return void
     * @Description
     * @Author zsj
     * @Date 2022-03-24 9:53
     **/
    @Override
    public void handleMessage(String message) {
        logger.info("接收到mqtt设备回复执行结果，消息：{}", message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        JSONObject body = jsonObject.getJSONObject("body");
        if (null != body) {
            //TODO 查询类型的应答
            return;
        }
        //设置类型的应答，直接入库
        //下发命令编号
        Long cmdId = jsonObject.getLong("cmd_id");
        QueryWrapper<TDeviceCmdRequest> cmdRequestQueryWrapper = new QueryWrapper<>();
        cmdRequestQueryWrapper.eq("request_num", cmdId);
        TDeviceCmdRequest cmdRequest = cmdRequestService.getOne(cmdRequestQueryWrapper);
        if (null == cmdRequest) {
            //无下发记录的回复
            return;
        }
        TDeviceCmdResponse cmdResponse = new TDeviceCmdResponse();
        cmdResponse.setDeviceNumber(cmdRequest.getDeviceNumber());
        Integer code = jsonObject.getInteger("code");
        cmdResponse.setResponseResult(0 == code ? 1 : 2);
        cmdResponse.setResponseCmd(jsonObject.toJSONString());
        cmdResponseService.saveCmdResponseAndDelCmdStatus(cmdResponse);
    }
}